package com.example.guiguiapplicatio.api;

import static com.example.guiguiapplicatio.api.GetCountTotalApi.ip;

import android.graphics.Bitmap;
import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.InsertRecordCallback;
import com.example.guiguiapplicatio.Response.FamilyarChooseService;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class InsertFamilySigningApi {
    private final Gson gson = new Gson();
    private AllCallback FamilySigning;
    private  InsertRecordCallback insertRecordCallback;


    public InsertFamilySigningApi(AllCallback familySigning) {
        FamilySigning = familySigning;
    }

    public void performPostImg(Bitmap bitmap, String filePath, List<FamilyarChooseService> familyarChooseServiceArrayList , String StaTime , String EndTime , int doctorId) {
        new Thread(() -> {
            String url = "http://"+ip +":9090/signing/addFamilySigning";
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json")
                    .build();

            // Save Bitmap to a file
            String savedFilePath = saveBitmapToFile(bitmap, filePath);

            if (savedFilePath != null) {
                // Create multipart request body
                RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), new File(savedFilePath));
                MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", savedFilePath, fileBody);

                // Convert SigningAdd to JSON string and add it to the request body
                String familyarChooseServiceArrayListJson = gson.toJson(familyarChooseServiceArrayList);
                requestBodyBuilder.addFormDataPart("FamilyarChooseService", familyarChooseServiceArrayListJson);
                requestBodyBuilder.addFormDataPart("StaTime", StaTime);
                requestBodyBuilder.addFormDataPart("EndTime", EndTime);
                requestBodyBuilder.addFormDataPart("doctorId", String.valueOf(doctorId));
                RequestBody requestBody = requestBodyBuilder.build();

                // Build the request
                Request request = new Request.Builder()
                        .url(url)
                        .headers(headers)
                        .post(requestBody)
                        .build();

                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
            } else {
                // Handle failure to save file
                Log.e("PostImgApi", "Failed to save bitmap to file.");
            }
        }).start();
    }


    // 保存 Bitmap 到文件，并返回文件路径
    private String saveBitmapToFile(Bitmap bitmap, String filePath) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            return filePath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            if (FamilySigning != null) {
                FamilySigning.onFailure(e.getMessage());
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Type jsonType = new TypeToken<ResponseBody<Object>>() {
            }.getType();
            String body = response.body().string();
            Log.d("info", body);
            ResponseBody<Object> dataResponseBody = gson.fromJson(body, jsonType);
            Log.d("info", dataResponseBody.toString());
            if (FamilySigning != null) {
                try {
                    FamilySigning.onSuccess(dataResponseBody);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
}
